package com.macro.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.IPage;
import com.macro.mall.common.api.CommonPageQuery;
import com.macro.mall.dao.PmsProductCategoryAttributeRelationDao;
import com.macro.mall.dao.PmsProductCategoryDao;
import com.macro.mall.dao.pms.PmsProductCategoryAttributeRelationMapper;
import com.macro.mall.dao.pms.PmsProductCategoryMapper;
import com.macro.mall.dao.pms.PmsProductMapper;
import com.macro.mall.dto.PmsProductCategoryDto;
import com.macro.mall.dto.PmsProductCategoryParam;
import com.macro.mall.dto.PmsProductCategoryTreeItemDto;
import com.macro.mall.dto.PmsProductCategoryWithChildrenItemDto;
import com.macro.mall.model.pms.*;
import com.macro.mall.service.PmsProductCategoryService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品分类管理Service实现类
 * Created by macro on 2018/4/26.
 */
@Service
public class PmsProductCategoryServiceImpl  extends ServiceImpl<PmsProductCategoryMapper, PmsProductCategoryDO> implements PmsProductCategoryService {
    @Autowired
    private PmsProductCategoryMapper productCategoryMapper;
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsProductCategoryAttributeRelationDao productCategoryAttributeRelationDao;
    @Autowired
    private PmsProductCategoryAttributeRelationMapper productCategoryAttributeRelationMapper;
    @Autowired
    private PmsProductCategoryDao productCategoryDao;
    @Override
    public int create(PmsProductCategoryParam pmsProductCategoryParam) {
        PmsProductCategoryDO productCategory = new PmsProductCategoryDO();
        productCategory.setProductCount(0);
        BeanUtils.copyProperties(pmsProductCategoryParam, productCategory);
        //没有父分类时为一级分类
        setCategoryLevel(productCategory);
        int count = productCategoryMapper.insertSelective(productCategory);
        //创建筛选属性关联
        List<Long> productAttributeIdList = pmsProductCategoryParam.getProductAttributeIdList();
        if(!CollectionUtils.isEmpty(productAttributeIdList)){
            insertRelationList(productCategory.getId(), productAttributeIdList);
        }
        return count;
    }

    /**
     * 批量插入商品分类与筛选属性关系表
     * @param productCategoryId 商品分类id
     * @param productAttributeIdList 相关商品筛选属性id集合
     */
    private void insertRelationList(Long productCategoryId, List<Long> productAttributeIdList) {
        List<PmsProductCategoryAttributeRelationDO> relationList = new ArrayList<>();
        for (Long productAttrId : productAttributeIdList) {
            PmsProductCategoryAttributeRelationDO relation = new PmsProductCategoryAttributeRelationDO();
            relation.setProductAttributeId(productAttrId);
            relation.setProductCategoryId(productCategoryId);
            relationList.add(relation);
        }
        productCategoryAttributeRelationDao.insertList(relationList);
    }

    @Override
    public int update(Long id, PmsProductCategoryParam pmsProductCategoryParam) {
        PmsProductCategoryDO productCategory = new PmsProductCategoryDO();
        productCategory.setId(id);
        BeanUtils.copyProperties(pmsProductCategoryParam, productCategory);
        setCategoryLevel(productCategory);
        //更新商品分类时要更新商品中的名称
        PmsProductDO product = new PmsProductDO();
        product.setProductCategoryName(productCategory.getName());
        PmsProductQuery example = new PmsProductQuery();
        example.createCriteria().andProductCategoryIdEqualTo(id);
        productMapper.updateByExampleSelective(product,example);
        //同时更新筛选属性的信息
        if(!CollectionUtils.isEmpty(pmsProductCategoryParam.getProductAttributeIdList())){
            PmsProductCategoryAttributeRelationQuery relationExample = new PmsProductCategoryAttributeRelationQuery();
            relationExample.createCriteria().andProductCategoryIdEqualTo(id);
            productCategoryAttributeRelationMapper.deleteByExample(relationExample);
            insertRelationList(id,pmsProductCategoryParam.getProductAttributeIdList());
        }else{
            PmsProductCategoryAttributeRelationQuery relationExample = new PmsProductCategoryAttributeRelationQuery();
            relationExample.createCriteria().andProductCategoryIdEqualTo(id);
            productCategoryAttributeRelationMapper.deleteByExample(relationExample);
        }
        return productCategoryMapper.updateByPrimaryKeySelective(productCategory);
    }

    @Override
    public Page<PmsProductCategoryDto> getList(Page<PmsProductCategoryDO> page, PmsProductCategoryQuery param) {
        List<PmsProductCategoryDO> list = productCategoryMapper.listByCondition(page,param);
        List<PmsProductCategoryDto> returnList = new ArrayList<>();
        list.forEach(item->{
            PmsProductCategoryDto dto = new PmsProductCategoryDto();
            BeanUtils.copyProperties(item,dto);
            returnList.add(dto);
        });
        Page<PmsProductCategoryDto> returnPage = new Page<>();
        returnPage.setRecords(returnList);
        return  returnPage;
    }

    @Override
    public int delete(Long id) {
        return productCategoryMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PmsProductCategoryDO getItem(Long id) {
        return productCategoryMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateNavStatus(List<Long> ids, Integer navStatus) {
        PmsProductCategoryDO productCategory = new PmsProductCategoryDO();
        productCategory.setNavStatus(navStatus);
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.createCriteria().andIdIn(ids);
        return productCategoryMapper.updateByExampleSelective(productCategory, example);
    }

    @Override
    public int updateShowStatus(List<Long> ids, Integer showStatus) {
        PmsProductCategoryDO productCategory = new PmsProductCategoryDO();
        productCategory.setShowStatus(showStatus);
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.createCriteria().andIdIn(ids);
        return productCategoryMapper.updateByExampleSelective(productCategory, example);
    }

    @Override
    public List<PmsProductCategoryWithChildrenItemDto> listWithChildren() {
        return productCategoryDao.listWithChildren();
    }


    @Override
    public List<PmsProductCategoryTreeItemDto> listAllCategoryTree() {
        List<PmsProductCategoryTreeItemDto>  list = productCategoryDao.listAllCategoryWithMapping();
        List<PmsProductCategoryTreeItemDto> resultList = buildProductCategoryTree(list);
        return resultList;
    }

    @Override
    public List<PmsProductCategoryTreeItemDto> listAllCategoryTreeWithAttributeConfig() {
        List<PmsProductCategoryDO>  list = productCategoryDao.listAllCategory();
        List<Long> lastNodeIdList = new ArrayList<>();
        List<PmsProductCategoryTreeItemDto> treeList =list.stream().map(item -> {
            PmsProductCategoryTreeItemDto dto = new PmsProductCategoryTreeItemDto();
            BeanUtils.copyProperties(item, dto);
            if(dto.getLastNode().equals(1)){
                lastNodeIdList.add(dto.getId());
            }
            return dto;
        }).collect(Collectors.toList());
        //查询属性关联



        List<PmsProductCategoryTreeItemDto> resultList = buildProductCategoryTree(treeList);

        return resultList;
    }



    /**
     * 根据分类的parentId设置分类的level
     */
    private void setCategoryLevel(PmsProductCategoryDO productCategory) {
        //没有父分类时为一级分类
        if (productCategory.getParentId() == 0) {
            productCategory.setLevel(0);
        } else {
            //有父分类时选择根据父分类level设置
            PmsProductCategoryDO parentCategory = productCategoryMapper.selectByPrimaryKey(productCategory.getParentId());
            if (parentCategory != null) {
                productCategory.setLevel(parentCategory.getLevel() + 1);
            } else {
                productCategory.setLevel(0);
            }
        }
    }


    @NotNull
    private List<PmsProductCategoryTreeItemDto> buildProductCategoryTree(List<PmsProductCategoryTreeItemDto> treeList) {
        List<PmsProductCategoryTreeItemDto> resultList = new ArrayList<>();
        Map<Long, PmsProductCategoryTreeItemDto> map = treeList.stream().collect(Collectors.toMap(PmsProductCategoryTreeItemDto::getId, item -> item));

        for (PmsProductCategoryTreeItemDto dto : treeList) {
            Long parentId = dto.getParentId();
            if (parentId == null || map.get(parentId) == null) {
                resultList.add(dto);
                continue;
            }
            PmsProductCategoryTreeItemDto parent = map.get(parentId);
            if (parent.getChildren() == null) {
                parent.setChildren(new ArrayList<>());
            }
            parent.getChildren().add(dto);
        }
        return resultList;
    }
}
